<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="预约人姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="预约人手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入预约人手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="预约时间" prop="time">
        <el-date-picker clearable v-model="queryParams.time" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 新增预约按钮 -->
    <div style="text-align: right; margin-bottom: 10px;">
      <el-button type="primary" icon="Plus" @click="handleAdd">新增预约</el-button>
    </div>

    <el-table v-loading="loading" :data="reservationList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="序号" align="center" type="index" width="60px" />
      <el-table-column label="预约人姓名" align="center" prop="name" />
      <el-table-column label="预约人手机号" align="center" prop="mobile" />
      <el-table-column label="预约时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="探访人" align="center" prop="visitor" />
      <!-- <el-table-column label="预约类型, 0:参观预约，1:探访预约" align="center" prop="type" /> -->
      <el-table-column label="预约类型" align="center" prop="type" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 0" type="success">参观预约</el-tag>
          <el-tag v-else-if="scope.row.type === 1" type="warning">探访预约</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="预约状态，0：待报道，1：已完成，2：取消，3：过期" align="center" prop="status" /> -->
      <el-table-column label="预约状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">待报道</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">已完成</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已取消</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="info">已过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改预约信息对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="120px" size="medium">
        <el-form-item label="预约人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入预约人姓名" />
        </el-form-item>
        <el-form-item label="预约人手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入预约人手机号" />
        </el-form-item>
        <el-form-item label="预约时间" prop="time">
          <el-row :gutter="18">
            <el-col :span="20">
              <el-form-item label="预约日期" label-width="80" style="margin-bottom: 14px;">
                <el-date-picker v-model="form.date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="预约时段" label-width="80" style="margin-bottom: 14px;">
                <el-select v-model="form.period" placeholder="请选择时间" style="width: 100%">
                  <el-option-group v-for="group in timeOptions" :key="group.label" :label="group.label">
                    <el-option v-for="item in group.options" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-option-group>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="探访人" prop="visitor">
          <el-input v-model="form.visitor" placeholder="请输入探访人" />
        </el-form-item>
        <el-form-item label="预约类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择预约类型">
            <el-option label="参观预约" :value="0" />
            <el-option label="探访预约" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import { listReservation, getReservation, delReservation, addReservation, updateReservation } from "@/api/nursing/reservation";

const { proxy } = getCurrentInstance();

const reservationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    mobile: null,
    time: null,
    visitor: null,
    type: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "预约人姓名不能为空", trigger: "blur" }
    ],
    mobile: [
      { required: true, message: "预约人手机号不能为空", trigger: "blur" },
      { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    date: [
      { required: true, message: "预约日期不能为空", trigger: "blur" }
    ],
    period: [
      { required: true, message: "预约时间段不能为空", trigger: "blur" }
    ],
    visitor: [
      { required: true, message: "探访人不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "请选择预约类型", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择预约状态", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 时间段选择
const timeOptions = [
  {
    label: '上午',
    options: [
      { label: '08:00', value: '08:00' },
      { label: '08:30', value: '08:30' },
      { label: '09:00', value: '09:00' },
      { label: '09:30', value: '09:30' },
      { label: '10:00', value: '10:00' },
      { label: '10:30', value: '10:30' },
      { label: '11:00', value: '11:00' },
      { label: '11:30', value: '11:30' },
      { label: '12:00', value: '12:00' },
    ]
  },
  {
    label: '下午',
    options: [
      { label: '12:30', value: '12:30' },
      { label: '13:00', value: '13:00' },
      { label: '13:30', value: '13:30' },
      { label: '14:00', value: '14:00' },
      { label: '14:30', value: '14:30' },
      { label: '15:00', value: '15:00' },
      { label: '15:30', value: '15:30' },
      { label: '16:00', value: '16:00' },
      { label: '16:30', value: '16:30' },
      { label: '17:00', value: '17:00' },
      { label: '17:30', value: '17:30' },
      { label: '18:00', value: '18:00' },
    ]
  }
];

/** 查询预约信息列表 */
function getList() {
  loading.value = true;
  listReservation(queryParams.value).then(response => {
    reservationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    mobile: null,
    date: null,       // 预约日期
    period: null,      // 预约时间段
    time: null,
    visitor: null,
    type: null,
    status: 0,        // ✅ 新增默认值
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("reservationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();

  const _id = row.id || ids.value
  getReservation(_id).then(response => {
    const data = response.data;

    // ✅ 拆分完整时间字段为 date 和 period
    if (data.time && data.time.includes(" ")) {
      const [date, period] = data.time.split(" ");
      data.date = date;
      data.period = period.slice(0, 5); // 去除秒数部分，保留 HH:mm
    }

    form.value = data;
    open.value = true;
    title.value = "修改预约信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reservationRef"].validate(valid => {
    if (valid) {

      if (!form.value.date || !form.value.period) {
        proxy.$modal.msgError("请选择完整的预约时间和日期");
        return;
      }

      // 拼接时间为完整的时间格式
      const fullTime = `${form.value.date} ${form.value.period}:00`;

      form.value.time = fullTime;

      if (form.value.id != null) {
        updateReservation(form.value).then(response => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        addReservation(form.value).then(response => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除预约信息编号为"' + _ids + '"的数据项？').then(function () {
    return delReservation(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getList();
</script>
